# -*- coding : utf_8 -*-
'''
=======================================
Time : 2025/4/1 18:39
Author : 田霄汉
Email : 522989570@qq.com
File : yaml_util.py
Project : unittest_demo
=======================================
'''
import os

import yaml

class YamlUtil:

    @classmethod
    def read_yaml(cls, yaml_path, key):
        """
        读取yaml文件中key的value
        :param yaml_name: yaml文件路径
        :param key: yaml中的key
        :return: key对应的value
        """
        try:
            with open(file=yaml_path, mode='r', encoding='utf-8') as f:
                content = yaml.load(stream=f, Loader=yaml.Loader)
                return content.get(key)
        except Exception as e:
            print(f"报错信息：{e}")

    @classmethod
    def read_yaml_nokey(cls, yaml_path):
        """
        读取yaml文件中全部信息
        :param yaml_name: yaml文件路径
        :return: yaml文件中的数据
        """
        try:
            with open(file=yaml_path, mode='r', encoding='utf-8') as f:
                content = yaml.load(stream=f, Loader=yaml.Loader)
                return content
        except Exception as e:
            print(f"报错信息：{e}")

    @classmethod
    def write_yaml(cls, yaml_path, data):
        """
        以清空的方式写入yaml文件中
        :param data: 需要写入的数据
        :param yaml_name: yaml文件路径
        :return: None
        """
        try:
            with open(file=yaml_path, mode='w', encoding='utf-8') as f:
                yaml.dump(data=data, stream=f, Dumper=yaml.Dumper, allow_unicode=True)
                f.close()
        except Exception as e:
            print(f'报错信息：{e}')

    @classmethod
    def write_yaml_add(cls, yaml_path, data):
        """
        以新增的方式写入数据到yaml文件
        :param yaml_path: yaml文件路径
        :param data: 写入数据内容
        :return: None
        """
        try:
            with open(file=yaml_path, mode='a', encoding='utf-8') as f:
                yaml.dump(data=data, stream=f, Dumper=yaml.Dumper, allow_unicode=True)
                f.close()
        except Exception as e:
            print(f'错误信息：{e}')

    @classmethod
    def clear_yaml(cls, yaml_path):
        """
        清空yaml文件内容
        :return: None
        """
        try:
            with open(file=yaml_path, mode='w', encoding='utf-8') as f:
                f.truncate()
                f.close()
        except Exception as e:
            print(f'错误信息：{e}')